<!DOCTYPE html>
<html>
  <head>
    <title>下载表情预览</title>

    <style>
      /* 更新分类容器为flex布局 */
      body {
        font-family: Arial, sans-serif;
        background-color: #f8fafc;
        color: #374151;
        margin: 0;
        padding: 20px;
      }
      #imageContainer {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: 30px;
        padding: 20px;
      }

      /* 重写图片网格为flex布局 */
      .image-grid {
        display: flex;
        flex-wrap: wrap;
        gap: 15px;
        padding: 15px;
        height: 300px;
        overflow: auto;

      }

      /* 调整图片项flex属性 */
      .image-item {
        flex: 0 0 auto;
        width: 20px;
        height: 20px;
        object-fit: contain;
        background: #f1f5f9;
        padding: 6px;
        border-radius: 6px;
        transition: transform 0.2s ease-in-out;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      }

      /* 保留hover效果 */
      .image-item:hover {
        transform: scale(1.1);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        z-index: 1;
      }

      /* 优化分类区块 */
      .category-section {
        width: 1400px;
        padding: 10px;
        height:400px;
        background: white;
        border-radius: 12px;
        border:1px solid #e2e8f0;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
      }
    </style>
  </head>
  <body>
    <h1>已下载图片预览</h1>
    <div id="imageContainer"></div>

    <script>
      async function loadImages() {
        try {
          const container = document.getElementById("imageContainer");

          // 确保使用正确的base路径
          const basePath = "/downloads";
          const response = await fetch(basePath);
          if (!response.ok) throw new Error(`无法访问 ${basePath} 目录`);

          const text = await response.text();
          const parser = new DOMParser();
          const doc = parser.parseFromString(text, "text/html");

          // 获取所有子目录链接
          const links = Array.from(doc.querySelectorAll("a"));
          console.log(
            "所有链接:",
            links.map((a) => a.href)
          );

          // 过滤并处理子目录路径
          const subDirs = links
            .map((a) => {
              try {
                const url = new URL(a, window.location.href);
                console.log(
                  "解析URL:",
                  url,
                  "a",
                  a.href,
                  "window",
                  window.location.href
                );
                // 修复路径处理：保留服务器返回的原始路径格式
                return url.pathname; // 直接使用解析后的pathname
              } catch {
                return null;
              }
            })
            .filter(
              (path) =>
                // console.log('过滤路径:', path,path.startsWith(basePath.replace(/\/$/, '')),path !== basePath)
                path &&
                // 放宽路径匹配条件：移除斜杠结尾要求，改为包含判断
                path.startsWith(basePath.replace(/\/$/, "")) && // 移除basePath结尾斜杠
                path !== basePath &&
                path.split("/").length > basePath.split("/").length // 确保是子目录
            );

          console.log("有效子目录:", subDirs);

          // 为每个子目录创建区块
          for (const dir of subDirs) {
            try {
              const dirResponse = await fetch(dir);
              console.log("Fetching:", dir, dirResponse);
              if (!dirResponse.ok) continue;

              const dirText = await dirResponse.text();
              const dirDoc = parser.parseFromString(dirText, "text/html");

              // 创建分类区块
              const section = document.createElement("div");
              section.className = "category-section";

              // 添加标题
              const title = document.createElement("h2");
              title.className = "category-title";
              title.textContent = decodeURIComponent(
                dir.split("/").filter(Boolean).pop()
              );
              section.appendChild(title);

              // 创建图片网格
              const grid = document.createElement("div");
              grid.className = "image-grid";

              // 添加图片
              Array.from(dirDoc.querySelectorAll("a"))
                .map((a) => a.href)
                .filter((href) => {
                  const ext = href.split(".").pop().toLowerCase();
                  return ["jpeg", "jpg", "gif", "png", "webp"].includes(ext);
                })
                .forEach((href) => {
                  const img = new Image();
                  img.className = "image-item";

                  // 修正图片路径处理
                  const imgUrl = new URL(href, window.location.href);
                  img.src = imgUrl.href;
                  img.alt = "下载的图片";

                  img.onerror = function () {
                    console.error("图片加载失败:", imgUrl.href);
                    this.style.display = "none";
                  };

                  // 删除以下两行尺寸设置代码
                  img.onload = function () {
                    // 完全由CSS控制尺寸，无需JS设置
                  };

                  grid.appendChild(img);
                });

              section.appendChild(grid);
              container.appendChild(section);
            } catch (dirError) {
              console.error("处理目录时出错:", dir, dirError);
            }
          }
        } catch (error) {
          console.error("加载图片失败:", error);
          container.innerHTML = `<p>请通过本地Web服务器访问本页面</p>
                    <p>运行命令：<code>npx http-server -o</code></p>`;
        }
      }
      loadImages();
    </script>
  </body>
</html>
